package intercepter

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"go.opentelemetry.io/otel/trace"
)

/*
   @author:zhongyang
   @date:2023/8/13
   @description:用于生成traceId
*/

// SetTraceId 用于设置traceId的拦截器
func SetTraceId(logger log.Logger) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if span := trace.SpanContextFromContext(ctx); span.HasTraceID() {
				_ = log.WithContext(ctx, logger).Log(log.LevelInfo,
					"trace.id", span.TraceID().String(),
				)
			}
			return handler(ctx, req)
		}
	}
}
